package com.example.mqmanager.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
public class FileManagerService {

    private static final Logger logger = LoggerFactory.getLogger(FileManagerService.class);

    /**
     * 分页读取文件内容（使用默认分页大小200行）
     * 
     * @param filePath 文件路径
     * @param page 页码（从1开始）
     * @return 文件内容和分页信息
     */
    public Map<String, Object> getFileContent(String filePath, int page) throws IOException {
        return getFileContent(filePath, page, 200);
    }
    
    /**
     * 分页读取文件内容
     * 
     * @param filePath 文件路径
     * @param page 页码（从1开始）
     * @param pageSize 每页行数
     * @return 文件内容和分页信息
     */
    public Map<String, Object> getFileContent(String filePath, int page, int pageSize) throws IOException {
        Map<String, Object> result = new HashMap<>();
        
        // 检查文件是否存在
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new FileNotFoundException("文件不存在: " + filePath);
        }
        
        // 检查是否为文件
        if (!Files.isRegularFile(path)) {
            throw new IllegalArgumentException("指定路径不是文件: " + filePath);
        }
        
        List<String> lines = new ArrayList<>();
        long totalLines = 0;
        long startPos = (page - 1) * pageSize;
        long endPos = startPos + pageSize;
        
        // 使用缓冲流读取文件
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath), StandardCharsets.UTF_8))) {
            
            String line;
            long lineNumber = 0;
            
            // 跳过前面的行
            while (lineNumber < startPos && (line = reader.readLine()) != null) {
                lineNumber++;
            }
            
            // 读取当前页的行
            while (lineNumber < endPos && (line = reader.readLine()) != null) {
                lines.add(line);
                lineNumber++;
            }
            
            // 继续计算总行数
            while (reader.readLine() != null) {
                lineNumber++;
            }
            
            totalLines = lineNumber;
        }
        
        result.put("lines", lines);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        result.put("totalLines", totalLines);
        result.put("totalPages", (totalLines + pageSize - 1) / pageSize);
        result.put("filePath", filePath);
        
        return result;
    }
    
    /**
     * 获取文件信息
     * 
     * @param filePath 文件路径
     * @return 文件信息
     */
    public Map<String, Object> getFileInfo(String filePath) throws IOException {
        Map<String, Object> result = new HashMap<>();
        
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new FileNotFoundException("文件不存在: " + filePath);
        }
        
        if (!Files.isRegularFile(path)) {
            throw new IllegalArgumentException("指定路径不是文件: " + filePath);
        }
        
        result.put("fileName", path.getFileName().toString());
        result.put("filePath", filePath);
        result.put("size", Files.size(path));
        result.put("lastModified", Files.getLastModifiedTime(path).toMillis());
        
        // 计算总行数
        long totalLines = 0;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath), StandardCharsets.UTF_8))) {
            while (reader.readLine() != null) {
                totalLines++;
            }
        }
        
        result.put("totalLines", totalLines);
        
        return result;
    }
}